const request = require('../../utils/request.js');  
const seeFm = require('../../config.js');
const util = require('../../utils/util.js');
const { addZero,$await } = require('../../utils/util');  // 格式化时间
import {commonAPI} from '../../api/channelLive/channelLive'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tab_data:[],
    room_number:'',
    start_time:'',
    room_id:'',
    atInfo:{},
    atShow:false,
    tabType:'chat',//底部tab聊天/短视频
    isLive:-1,//是否直播
    fullScreenFlag:false,//是否全屏
    playUrl:'',
    changeplayUrl:'',
    playType:1,
    pageDate:{},
    imgUrlImg:'',
    imgUrlAvatar:'',
    height:0,//短视频高度
    heightfather:0,
    heightchild:0,
    heightchild1:0,
    showAudioIcon:'1',//处理切直播间展示问题
    scrollLeft:0,
    top:-56,
    toastWord:'节目已结束，为您推荐精彩短视频',
    liveFlag:999,//默认都是直播已结束
    urgent_switch_type:-1,//是否应急
  },
  // 子组件告知是否要显示 @列表
  showAtlist(e){
    this.setData({atShow:e.detail})
  },
  // 子组件告知是切换直播间/视频/音频
  switchStreamDate(e){
    if(e.content.type === 3){
      this.setData({
        room_number:e.content.number
      })
      this.enter()
    }else if(e.content.type === 2){
      if(e.content.number === this.data.room_number){
        this.setData({
          ['pageDate.live_status']:2,
          playType:'2',
          showAudioIcon:'2',
          playUrl:this.data.pageDate.play_url.channel_audio_url
        })
      }else{
        this.setData({
          room_number:e.content.number
        })
        this.enter()
      }
    }
    else if(e.content.type === 1){
      if(e.content.number === this.data.room_number){
        this.setData({
          ['pageDate.live_status']:1,
          playType:'1',
          showAudioIcon:'1',
          playUrl:this.data.pageDate.play_url.flv_url
        })
      }else{
        this.setData({
          room_number:e.content.number
        })
        this.enter()
      }
    }
    this.setData({switchStream:e})
  },
  // 紧急切换按钮逻辑
  urgentSwitchDate(e){
    console.log(e);
    if(e.content.type == 1){
      this.setData({
        urgent_switch_type:1,
        playUrl:e.content.url
      })
    }else{
      this.setData({
        urgent_switch_type:0,
        playUrl:this.data.changeplayUrl
      })
    }
  },
  // 选中的要@的用户信息
  atMsg(e){
    this.setData({atInfo:e.detail})
  },
  //切换聊天/短视频
  changeTab:function(e){
    console.log(e.currentTarget.dataset['type'])
    this.setData({
      tabType:e.currentTarget.dataset['type']
    })
    console.log(this.data.tabType)
  },
  //收藏
  async collection(e){
    const { is_follow } = e.currentTarget.dataset;
    let params = {
      'channel_number':this.data.pageDate.channel_info.channel_number,
      'type':is_follow
    }
    const [err,res] = await $await(commonAPI.follow({...params}))
      if(res){
        if(is_follow == '1'){
          wx.showToast({
            title: '收藏成功',
            duration: 1000,
            mask:true
          })
          this.setData({
            ['pageDate.channel_info.is_follow']:1
          })
        }else{
          wx.showToast({
            title: '取消成功',
            duration: 1000,
            mask:true
          })
          this.setData({
            ['pageDate.channel_info.is_follow']:0
          })
        }
      }
  },
  //校验接口
  async check(number){
    let params = {
      'number':number,
    }
    const [err,res] = await $await(commonAPI.check({...params}))
      if(res){
        for(let i=0;i<this.data.pageDate.programmer_list.length;i++){
          if(this.data.pageDate.programmer_list[i].programme_number == res.live_number && this.data.pageDate.programmer_list[i].start_time ==res.start_time){
            this.setData({
              ['pageDate.programmer_list['+i+'].is_living']:1
            })
          }else{
            this.setData({
              ['pageDate.programmer_list['+i+'].is_living']:0
            })
          }
        }
        if(res.status == '1'){
          this.setData({
            isLive:1,
            room_number:number,
            start_time:res.start_time
          })
        }else{
          this.setData({
            isLive:0,
            room_number:number
          })
          this.slideIn();//调用动画--滑出
          
        }
        
      }
  },
  //返回上一级
  back:function(){
    var pages = getCurrentPages();
    var beforePage = pages[pages.length - 2];
    // beforePage.loadData();
    wx.navigateBack({
      delta: 1,
    })
  },
  //点赞
  async star(e){
    const { is_follow } = e.currentTarget.dataset;
    let params = {
      'number':this.data.pageDate.number,
      'period':this.data.pageDate.period
    }
    const [err,res] = await $await(commonAPI.star({...params}))
      if(res){
        this.setData({
          ['pageDate.is_stars']:2
        })
        setTimeout(() => {
          this.setData({
            ['pageDate.is_stars']:1
          })
        }, 1000);
      }
  },
  //切换期数
  changePro:function(e) {
    this.check(e.currentTarget.dataset['room_number']);
    
    for(let i=0;i<this.data.pageDate.programmer_list.length;i++){
      if(this.data.pageDate.programmer_list[i].programme_number == e.currentTarget.dataset['room_number'] && this.data.pageDate.programmer_list[i].start_time == e.currentTarget.dataset['start_time']){
        if(i<this.data.liveFlag){
          this.setData({
            toastWord:'节目已结束，为您推荐精彩短视频'
          })
        }else if(i>this.data.liveFlag){
          this.setData({
            toastWord:'直播暂未开始，为您推荐精彩短视频'
          })
        }
        this.setData({
          scrollLeft:i*246+'rpx',
          ['pageDate.programmer_list['+i+'].checkbox']:1
        })
      }else{
        this.setData({
          ['pageDate.programmer_list['+i+'].checkbox']:0
        })
      }
    }
  },
  //全屏
  fullScreen:function(){
    let videoContext1 = wx.createLivePlayerContext('player');
    let that = this
    console.log(videoContext1)
    videoContext1.requestFullScreen({
      direction: 90,
      success (e) {
        that.setData({
          fullScreenFlag: true
        })
      }
    })
  },
  //退出全屏
  backFullScreen:function(){
    let that = this
    let videoContext1 = wx.createLivePlayerContext('player');
    videoContext1.exitFullScreen({
      success (e) {
        that.setData({
          fullScreenFlag: false
        })
      },
    })
  },
  //切换音视频
  checkPlay:function(e){
    console.log(e.currentTarget.dataset)
    if(e.currentTarget.dataset['playtype'] == '1'){
      this.setData({
        playType:'2',
        playUrl:this.data.pageDate.play_url.flv_audio_url
      })
      let videoContext1 = wx.createLivePlayerContext('player');
      videoContext1.stop();
      videoContext1.play();
    }else if(e.currentTarget.dataset['playtype'] == '2'){
      this.setData({
        playType:'1',
        playUrl:this.data.pageDate.play_url.flv_url
      })
      let videoContext1 = wx.createLivePlayerContext('player');
      videoContext1.stop();
      videoContext1.play();
    }
  },
  //进房
  async enter(){
    let params = {
      'number':this.data.room_number
    }
    const [err,res] = await $await(commonAPI.enter({...params}))
      if(res){
        wx.setNavigationBarTitle({
          title: res.channel_name
        })
        this.setData({
          imgUrlImg:seeFm.imgUrlImg,
          imgUrlAvatar:seeFm.imgUrlAvatar,
          isLive:res.is_live_ing,
          room_number:res.number,
          room_id:res.room_id,
          tab_data:res.tab_data,
          channel_id : res.channel_id,
          shop_url:res.shop_url,
          pageDate:res
        })
        for(let i=0;i<this.data.tab_data.length;i++){
          this.setData({
            ['tab_data['+i+'].tabType']:i+1
          })
        }
        if(res.live_status == '2'){
          this.setData({
            playUrl:this.data.pageDate.play_url.channel_audio_url,
            changeplayUrl:this.data.pageDate.play_url.channel_audio_url
          })
        }else{
          this.setData({
            playUrl:this.data.pageDate.play_url.flv_url,
            changeplayUrl:this.data.pageDate.play_url.flv_url
          })
        }
        if(Number(this.data.pageDate.viewers)<10000){
          this.setData({
            ['pageDate.viewers']:util.toFix(Number(this.data.pageDate.viewers),1000,'k')
          })
        }else{
          this.setData({
            ['pageDate.viewers']:util.toFix(Number(this.data.pageDate.viewers),10000,'w')
          })
        }
        let num = 0;
        for(let i=0;i<this.data.pageDate.programmer_list.length;i++){
          if(this.data.pageDate.programmer_list[i].is_living == '1'){
            this.setData({
              ['pageDate.programmer_list['+i+'].choice']:1,
              ['pageDate.programmer_list['+i+'].checkbox']:1,
              scrollLeft:i*246+'rpx',
              liveFlag:i,
              start_time:this.data.pageDate.programmer_list[i].start_time,
            })
          }else{
            num++;
            this.setData({
              ['pageDate.programmer_list['+i+'].choice']:0,
              ['pageDate.programmer_list['+i+'].checkbox']:0
            })
          }
        }
        if(res.type == '0'){
          this.setData({
            'playType':1
          })
        }else{
          this.setData({
            'playType':2
          })
        }
        if(res.live_status == '1'){
          this.setData({
            'playType':1
          })
        }else{
          this.setData({
            'playType':2
          })
        }
        //紧急切换按钮逻辑 
        if (num == this.data.pageDate.programmer_list.length){
          this.setData({
            ['this.data.pageDate.programmer_list'+[0]+'.choice']:1
          })
          this.setData({
            ['pageDate.programmer_list['+i+'].checkbox']:1
          })
        }
        if(res.urgent_switch_type === 1){
          this.setData({
            urgent_switch_type:1,
            playUrl:res.urgent_switch_url
          })
        }else{
          this.setData({
            urgent_switch_type:0,
          })
        }
      }
  },
  //动画 -- 滑入
  slideIn: function () {
    let timer = setInterval(()=>{
      if(this.data.top<0){
        this.setData({
          top:this.data.top +1
        })
      }else{
        clearInterval(timer);
        setTimeout(()=>{
          this.setData({
            top:-56
          })
          clearInterval();
        },3000)
        
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      room_number:options.number
    })
    this.enter();
    wx.event.on('cb_room',(data)=>{
			data.forEach(item =>{
				if(item.action === 'switchStream'){
					this.switchStreamDate(item)
				}else if(item.action === 'urgentSwitch'){
          this.urgentSwitchDate(item)
        }
			})
		})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let query = wx.createSelectorQuery();
    query.select('.header').boundingClientRect(rect=>{
      this.data.heightchild = rect.height;
    }).exec();
    let query1 = wx.createSelectorQuery();
    query1.select('.container').boundingClientRect(rect=>{
      this.data.heightfather= rect.height;
    }).exec();
    let query2 = wx.createSelectorQuery();
    query2.select('.programerList').boundingClientRect(rect=>{
      this.data.heightchild = rect.height;
      console.log(this.data.heightfather - this.data.heightchild - this.data.heightchild1)
    }).exec();

    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: async function () {
    wx.event.off('cb_room')
    await wx.exit_room()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})